package thread;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author Klys
 * @Date 2023/6/4 11:37
 * @Description
 * @Version 1.0
 */
@Slf4j
public class ThreadLocalTest01 {

    private static ThreadLocal<String> local = new ThreadLocal<String>();

    static void print(String str) {
        //打印当前线程中本地内存中变量的值
        System.out.println(str + " :" + local.get());
        //清除内存中的本地变量
        local.remove();
    }

    public static void main(String[] args) throws InterruptedException {
//        String s = new String("abc");
//        print(s);

        new Thread(() -> {
            ThreadLocalTest01.local.set("线程A修改");
            print("线程A");
            //清除后
            System.out.println("清除后：" + local.get());
            //线程A设置
            ThreadLocalTest01.local.set("线程A又修改");
            System.out.println("线程A又修改本地local:" + local.get());
        }, "A").start();

        Thread.sleep(3000);

        new Thread(() -> {
            System.out.println(ThreadLocalTest01.local.get());
            ThreadLocalTest01.local.set("线程B修改");
            print("线程B");
            //清除后
            System.out.println("清除后：" + local.get());
        }).start();
    }
}
